var qids = new Array();
var answers = new Array();

var mode;
var time;
var id;
var index;
var username;
var lastindex;


function change(){
    var spanTag = document.getElementById("countdown");
    var divTag = document.getElementsByClassName("modal-dialog")[0];

    var v = spanTag.innerText;
    spanTag.innerText = v - 1;

    if(spanTag.innerText == 0){
        clearInterval(id);
        index = divTag.getAttribute("id");
        var ansTag = divTag.getElementsByClassName("answer")[0];
        var answer = ansTag.value;
        var qid = divTag.getElementsByClassName("qid")[0].value;

        qids.push(qid);
        answers.push(answer);



        if(index != lastindex){
            show_next();
            id=setInterval(change,1000);
            document.getElementById("countdown").innerText = time;
        }else{
            jump_socre_page();
        }
    }
}

function write_history(username){

    ajaxRequest('writeAnswers.php','get',{qids:qids,answers:answers,username:username,mode:mode,time:time},function () {

    },function () {

    });
}

function jump_score_page(){

    function on_success(){
        alert(this.responseText);
        var pTag = document.createElement('p');
        pTag.innerText = this.responseText;
        listTag.appendChild(pTag);
    }
    function on_failure(){
        alert("fail")
    }

    var linkQids = arrayFormatLink('qids',qids);
    var linkAnswers = arrayFormatLink('answers',answers);

    if(username != '')
        write_history(username);

    window.location='score.php?'+linkQids+"&"+linkAnswers;
        //ajaxRequest('score.php','get',{qids:qids,answers:answers},on_success,on_failure);
        //ajaxRequest("test.php",'get',{x:"xx"},function ok(){alert(this.responseText);},function ko(){alert("fail")});

}

function show_next(){
    var divNode = document.getElementsByClassName("modal-dialog")[0];
    index = divNode.getAttribute("id");
    if(index != lastindex){
        document.getElementById("questions").removeChild(divNode);
        document.getElementsByClassName("modal-dialog")[0].style.visibility = "visible";
    }else{
        jump_score_page();
    }
}

function get_val(){
    var qid = document.getElementsByClassName("qid")[0].value;
    var answer = document.getElementsByClassName("answer")[0].value;
    qids.push(qid);
    answers.push(answer);
}

function normal_mode(){
    get_val();
    show_next();
}

function time_mode(){
    get_val();
    clearInterval(id);
    show_next();
    id=setInterval(change,1000);
    document.getElementById("countdown").innerText = time;
}

function click_next(){
    if(mode == "normal" ){
        normal_mode();
    }else{
        time_mode();
    }
}

// function click_next(inputTag){
//     var divTag = inputTag.parentNode;
//     index = divTag.getAttribute("id");
//
//     var ansTag = divTag.querySelector(".answer");
//     var answer = ansTag.value;
//     if(answer == ''){
//         alert("the answer is empty!!!");
//         console.info("empty");
//         return ;
//     }
//
//     var qid = divTag.querySelector(".qid").value;
//     qids.push(qid);
//     answers.push(answer);
//     if(index != lastindex){
//         clearInterval(id);
//         show_next(divTag);
//         if(mode=='time')
//         id=setInterval(change,1000);
//     }else{
//         clearInterval(id);
//         jump_socre_page();
//     }
// }

window.onload = function(){
    document.getElementById("0").style.visibility = "visible";
    mode = document.getElementById("mode").value;
    time = document.getElementById("time").value;
    lastindex = document.getElementById("num").value - 1;

    username = document.getElementById("username").value;



    if(mode === "time"){
        id= setInterval(change,1000);
        document.getElementById("countdown").innerText = time;

    }

}

function ajaxRequest(url,method,parameters,onSuccess,onFailure) {

    function getMethod(method) {
        if ( typeof method != "string" )
            throw method + ": bad method (choose 'GET' or 'POST')";
        method = method.trim().toLowerCase();
        if ( method != 'get' && method != 'post' )
            throw method + ": bad method (choose 'GET' or 'POST')";
        return method;
    }

    function getParameters(method,parameters) {
        if ( typeof parameters != "object" )
            throw method + ": bad parameters (must be an object)";
        if ( method === "get") {
            var params = [];
            for ( param in parameters ){
                if(parameters[params] instanceof Array === false)
                    params.push(param + "=" + encodeURIComponent(parameters[param]));
                 else{
                     params.push(param+"[]="+encodeURIComponent(parameters[param]));
                 }
            }

            return params.join("&");
        }
        else {
            var params = new FormData();
            for ( param in parameters ) {
                params.append(param,parameters[param]);
            }
            return params;
        }
    }

    method = getMethod(method);

    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    if ( onSuccess && onFailure ) {
        xmlhttp.onload = onSuccess;
        xmlhttp.onerror = onFailure;
    }

    if ( method === 'get' ) {
        if ( parameters == "" )
            xmlhttp.open("GET",url,true);
        else
            xmlhttp.open("GET",url + "?" + getParameters("get",parameters),true);
        xmlhttp.send();
    }
    else {
        xmlhttp.open("POST",url,true);
        xmlhttp.send(getParameters("post",parameters));
    }
}

function arrayFormatLink(key,array){//http:...?link[]=a&link[]=b
    var linkArray = [];
    for(var i = 0; i < array.length; i++){
        linkArray.push(key+"[]="+array[i])
    }
    return linkArray.join('&');
}


